package bigbeard.tools.net.utils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author bigbeard on 2022-10-10
 */

public class Utils {

    private static final int WAIT_SEND_TIME = 5;
    private static final int MAX_SEND_SIZE = 4096;

    public static final String WEB_SOCKET = "ws";
    public static final String TCP_CLIENT = "tcp";
    public static final String UDP_CLIENT = "udp";

    /**
     * 发送数据到对端
     *
     * @param socketChannel 发送数据所使用的通道
     * @param bytes         发送的数据
     * @return 真实发送的数据长度
     * @throws IOException 写通道失败
     */
    public static int write(SocketChannel socketChannel, byte[] bytes) throws IOException {
        int sendCount;

        ByteBuffer wrap = ByteBuffer.wrap(bytes);
        sendCount = socketChannel.write(wrap);

        while (sendCount < bytes.length) {
            int lastLen = bytes.length - sendCount;
            int len = Math.min(lastLen, MAX_SEND_SIZE);
            byte[] b = new byte[len];
            System.arraycopy(bytes, sendCount, b, 0, len);
            wrap = ByteBuffer.wrap(b);
            int write = socketChannel.write(wrap);
            if (write == 0) {
                try {
                    Thread.sleep(WAIT_SEND_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            sendCount += write;
        }
        return sendCount;
    }
}
